﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gueei.Gallery.Core.Entities;
using Gueei.Gallery.Core.Services;
using Gueei.Gallery.Web.Exceptions;
using Gueei.Gallery.Web.Models;
using Gueei.Gallery.Web.ViewModels;

namespace Gueei.Gallery.Web.Controllers
{
	public class UploadController : Controller
	{
		private IUserService UserService { get; set; }
		private readonly BatchImportService _batchImportService;
		private AlbumService AlbumService{get;set;}
		public UploadController(BatchImportService batchImportService, AlbumService albumService, IUserService userService)
		{
			_batchImportService = batchImportService;
			AlbumService = albumService;
			UserService = userService;
		}

		[HttpGet]
		[Authorize(Roles=Gallery.Security.GalleryRoles.Upload)]
		public ActionResult Batch()
		{
			var batchId = (Guid?)Session["BatchUploadId"];
			UploadBatch batch;
			if (!batchId.HasValue)
			{
				batch = _batchImportService.StartNewBatch();
				Session["BatchUploadId"] = batch.BatchId;
			}
			else
			{
				batch = _batchImportService.GetUploadBatch(batchId.Value);
				if (batch == null)
				{
					// Maybe expired?
					batch = _batchImportService.StartNewBatch();
					Session["BatchUploadId"] = batch.BatchId;
				}
			}

			batch.Creator = UserService.GetCurrentUser();

			var model = new BatchUploadViewModel();

			foreach (var temp in batch.TempImages)
			{
				model.Images.Add(new BatchTempImageViewModel {
					Id = temp.TempId,
					Name = temp.Name,
					Description = temp.Description,
					Tags = temp.Tags
				});
			}
			return View(model);
		}


		[HttpPost]
		public ActionResult Batch(BatchUploadViewModel model)
		{
			var batchId = (Guid?)Session["BatchUploadId"];
			if (!batchId.HasValue) return RedirectToAction("Batch");
			var batch = _batchImportService.GetUploadBatch(batchId.Value);
			if (batch == null) return RedirectToAction("Batch");

			if (ModelState.IsValid)
			{
				foreach (var image in model.Images)
				{
					var temp = batch.TempImages.Where(t=>t.TempId.Equals(image.Id)).SingleOrDefault();
					if (temp == null) continue;
					temp.Tags = image.Tags;
					temp.Name = image.Name;
					temp.Description = image.Description;
				}
				// Save!
				var images = _batchImportService.ConfirmBatch(batch);

				if (model.CreateNewAlbum)
				{
					AlbumService.CreateAlbum(model.NewAlbumName, images.ToList(), new Tag[] { });
				}
				Session.Remove("BatchUploadId");
				return RedirectToAction("Index", "Browse");
			}
			return View(model);
		}

		[HttpGet]
		public ActionResult _GetBatchFiles()
		{
			var batchId = (Guid?)Session["BatchUploadId"];
			if (!batchId.HasValue) return new JsonResult { Data = new { success = false, reason = "No batch is present" } };
			var batch = _batchImportService.GetUploadBatch(batchId.Value);
			if (batch == null) return new JsonResult { Data = new { success = false, reason = "Batch maybe expired." } };

			var model = new BatchUploadViewModel();

			foreach (var temp in batch.TempImages)
			{
				model.Images.Add(new BatchTempImageViewModel {
					Id = temp.TempId,
					Name = temp.Name,
					Description = temp.Description,
					Tags = temp.Tags
				});
			}
			return new JsonResult {
				JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
				Data = from img in batch.TempImages
					   select new {
						   Id = img.TempId,
						   Name = img.Name
					   }
			};
		}

		[HttpPost]
		public ActionResult _AsyncUpload(HttpPostedFileBase qqfile)
		{
			var batchId = (Guid?)Session["BatchUploadId"];
			if (batchId.HasValue)
			{
				var batch = _batchImportService.GetUploadBatch(batchId.Value);
				if (batch == null) return new JsonResult { Data = new { success = false, reason = "batch not found. try refresh browser." } };
				// Handler for non IE
				TempImage newImage;
				if (qqfile == null)
				{
					var fileName = Request["qqfile"];
					// then the file is from the raw stream
					newImage = _batchImportService.AddToBatch(batch, Request.InputStream, fileName);
				}
				else
				{
					newImage = _batchImportService.AddToBatch(batch, qqfile.InputStream, qqfile.FileName);
				}
				return new JsonResult {
					Data =
						new {
							success = true,
							Id = newImage.TempId,
							Name = newImage.Name
						}
				};
			}
			else
			{
				return new JsonResult { Data = new { success = false, reason = "batch not found. try refresh browser." } };
			}
		}

		[HttpGet]
		public ActionResult PreviewImage(Guid imageId)
		{
			var batchId = (Guid?)Session["BatchUploadId"];
			if (!batchId.HasValue) throw new ResourceNotFoundException("");
			try
			{
				string contentType;
				return new FileContentResult(_batchImportService.GetPreview(batchId.Value, imageId, out contentType),
					contentType);
			}
			catch
			{
				throw new ResourceNotFoundException("");
			}
		}
	}
}